#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import redis

# 连接池配置
pool = redis.ConnectionPool(
    host='localhost',
    port=6379,
    max_connections=10,
)

r = redis.Redis(
    host='localhost',   # Redis服务器IP
    port=6379,          # 端口
    db=0,               # 数据库索引（0-15）
    password='123456', # 密码（若无密码可省略）
    decode_responses=True,  # 自动解码返回值为字符串（默认bytes）
    connection_pool=pool # 连接池
)

def testString():
    # 字符串 String
    # 设置键值对
    r.set("user:1000", "我修院", ex=60) # 60秒后自动删除
    # 获取值
    value = r.get("user:1000")
    print(value.decode() if value else "Not found")
    # 计数器应用
    r.set("page_views", 0)
    r.incr("page_views") # 自增1
    print(r.get("page_views"))

def testHash():
    # 存储用户信息
    user_data = {'name': '李田所', 'age': 24, 'email': '114@514.com'}
    r.hset("user:2", mapping=user_data)

    # 获取单个字段
    name = r.hget("user:2", "name")
    print(name.decode())  # 注意 decode()

    # 获取所有字段
    user = r.hgetall("user:2")
    print({k.decode(): v.decode() for k, v in user.items()})

def testList():
    # 模拟任务队列
    r.rpush("task_queue", "process_data")
    r.rpush("task_queue", "send_email")
    # 消费任务
    task = r.lpop("task_queue")
    print(task.decode())
    # 获取任务长度
    queue_length = r.llen("task_queue")
    print(queue_length)

def testSet():
    # 存储文章标签
    r.sadd("article:10:tags", "tech", "database", "python")
    # 检查标签是否存在
    print(r.sismember("article:10:tags", "python"))
    # 获取所有标签
    tags = r.smembers("article:10:tags")
    print({tag.decode() for tag in tags})

def testZSet():
    # 游戏排行榜
    r.zadd("game_leaderboard", {"梦汨": 1000, "XiaoHai": 1100, "fxxker": 1050, "XQB": 10})
    # 获取前三名（降序）
    top_players = r.zrevrange("game_leaderboard", 0, 2, withscores=True)
    for player, score in top_players:
        print(f"{player.decode()}: {int(score)}")

def main():
    # testString()
    # testHash()
    # testList()
    # testSet()
    testZSet()

if __name__ == "__main__":
    main()